import { Component, ViewChild, Inject } from '@angular/core';
import { IonicPage, NavController,  ModalController, Content, Refresher } from 'ionic-angular';

import { Subscription } from 'rxjs/Subscription';
// service
import { HideBarsService } from '../../providers/utils/hideBars.service';
import { BorrowService } from '../../providers/service/borrow.service';

// 常量
import * as PageConstant from '../../constant/pageConstant';
import { Observable } from "rxjs/Observable";
import { Auth, User } from "../../providers/entity/user.model";

// 定义按钮常量
const BUTTON_TEXT= {
  INCREASE_LIMIT: '提升额度',
  TAKE_MONEY: '立即拿钱',
  PROGRESS: '借款进度',
};

/**
 * tab页面的还款新方案
 */
@IonicPage()
@Component({
  selector: 'page-borrow-money',
  templateUrl: 'borrow-money.html',
})
export class BorrowMoneyPage {

  // 提示文字
  private fabBtnText: string= BUTTON_TEXT.TAKE_MONEY;
  // 增加透明度
  private needAddaOpacity: boolean= false;
  // 持卡人信息
  private userInfo: any;

  // 借款picker
  @ViewChild('borrowPicker') borPicker: any;
  // 借款进度
  @ViewChild('borrowProgress') borProgress: any;
  // Refresher相关
  @ViewChild(Content) content: Content;
  @ViewChild(Refresher) refresher: Refresher;

  // 借款modal的数据
  private borrowPickerStore: any;

  // 借款modal状态
  private borrowModalStatus: any;
  // 借款modal的数据
  private borrowProgressStore: any;

  // 背景图数组
  private borrowQuotaList: Array<any>;

  // 若下来未完成不能点击下一步
  private isCanNextBool: boolean;

  // 监听store
  private authSubscription: Subscription;
  // 订阅picker数据
  private pickerSubscription: Subscription;
  // 订阅进度数据
  private progressSubscription: Subscription;
  constructor(
    private navCtrl: NavController,
    private modalCtrl: ModalController,
    private hideBars: HideBarsService,
    @Inject('auth') private authService,
    @Inject('user') private userService,
    private borrowService: BorrowService,
  )
  {
    // 赋值背景数组默认值
    this.borrowQuotaList=[
      {
        backImg: 'assets/img/gold-card.png',
        footText: '按时还款3笔后,即可享受升级服务',
        limit: 1200,
        lock: false,
      },
      {
        backImg: 'assets/img/white-gold-card.png',
        footText: '额度提升25%,成功还款满3笔即可解锁',
        limit: 1200,
        lock: false,
      },
      {
        backImg: 'assets/img/diamond-card.png',
        footText: '额度提升60%,成功还款满6笔即可解锁',
        limit: 1200,
        lock: false,
      },
      {
        backImg: 'assets/img/black-card.png',
        footText: '额度翻倍,成功还款满9笔即可解锁',
        limit: 3000,
        lock: false,
      },
    ];
  }


  /*** 页面进入
   * */
  ionViewWillEnter()
  {
    this.getBorrowPickerStore();
    this.getBorrowProgressStore();
    this.initUserAuthSubs();
  }
  /*** 初始化用户登录权限和认证信息监听
  * */
  initUserAuthSubs()
  {
    this.authSubscription=
      Observable.combineLatest(this.userService.getUser(),
        this.authService.getAuth(),(user: User, auth: Auth)=>({...user,...auth}))
        .filter(data=> !data.hasError
          && !!data.idState
          && !!data.contactState
          && !!data.bankState
          && data.mobileState===2
        )
        .map(data=> ({...data.idInfo,...data.bankInfo}))
        .subscribe(result=>{
          this.userInfo= {...result};
        })
  }

  /*** 订阅借款picker Store的数据
   * */
  private getBorrowPickerStore()
  {
    this.pickerSubscription=
      this.borrowService.getBorrow()
        .filter(borrow=> borrow.config.length>0
          && borrow.selectedIndex.length>0
          && !borrow.borrowModalStatus // 状态更改,进入picker
        )
        .map(borrow=> {
          const { selectedIndex, config, borrowModalStatus, quota }= borrow;
          return { selectedIndex, config, borrowModalStatus, quota }
        })
        .subscribe(result=>{
          this.borrowQuotaList= [...result.quota ];
          this.borrowModalStatus= result.borrowModalStatus;
          this.borrowPickerStore= {...result};
          this.fabBtnText= BUTTON_TEXT.TAKE_MONEY;
          this.isCanNextBool= true;
        });
  }

  /*** 订阅借款progress相关的数据
  * */
  private getBorrowProgressStore()
  {
    this.progressSubscription=
    this.borrowService.getBorrow()
      .filter(borrow=> borrow.progress.length>0 && !!borrow.borrowModalStatus)
      .map(borrow=> {
        const { borrowModalStatus, progress, time, quota }= borrow;
        return { borrowModalStatus, progress, time, quota }
      })
      .subscribe(result=> {
        this.borrowQuotaList= [...result.quota ];
        this.borrowModalStatus= result.borrowModalStatus;
        this.borrowProgressStore= {...result};
        // 进入审核流程
        this.fabBtnText= BUTTON_TEXT.PROGRESS;
        this.isCanNextBool= true;
    });
  }

  /*** 检查认证状态去服务器获取模态数据
   * */
  private setBorrowStoreFromBack(refresher: Refresher): void
  {
    this.authService.checkHasLogin()
      .then(status=> {
        if(!status){ // 未登录
          this.borrowService.getAppBorrowPickerDefault(refresher);
          return;
        }
        this.borrowService.getUserBorrowModalDate(refresher);
      });
  }

  ionViewDidEnter()
  {
    this.refresher._top = this.content.contentTop + 'px';
    this.refresher.state = 'ready';
    this.refresher._onEnd();
    this.hideBars.initTabBarElementArray();
  }

  /*** 页面离开
   * */
  ionViewWillLeave()
  {
    this.removeSubscription();
  }

  /*** 移除监听
   * */
  private removeSubscription(): void
  {
    if(typeof this.authSubscription !== 'undefined')
      this.authSubscription.unsubscribe();

    if(typeof this.pickerSubscription !== 'undefined')
      this.pickerSubscription.unsubscribe();

    if(typeof this.progressSubscription !== 'undefined')
      this.progressSubscription.unsubscribe();
  }
  /** 打开疑问
   * */
  doHelp(): void
  {
    this.navCtrl.push(PageConstant.AboutPage);
  }

  /*** 显示模态选择
   * */
  executeBorrowModal(): void
  {
    // 若下拉未完成, 不能下一步
    if(!this.isCanNextBool) return;
    this.doContentTop();

    this.addaOpacityByTimer();
    // modal状态为1为借款进度状态 0为借款
    if(!this.borrowModalStatus)
    {
      this.changeBorrowPicker();
      return;
    }
    this.changeBorrowProgress();
  }
  /* 去首页
  * */
  private doContentTop()
  {
    setTimeout(() => {
      if (this.content.scrollToTop) {
        this.content.scrollToTop();
      }
    }, 400)
  }

  /*** 定时器增加透明度
  * */
  private addaOpacityByTimer(): void
  {
    this.needAddaOpacity= true;
    let timer= setTimeout(()=>{
      this.needAddaOpacity= false;
      clearTimeout(timer);
      timer= null;
    },300);
  }

  /*** borrow-picker模态操作
  * */
  private changeBorrowPicker(): void
  {
    if(this.fabBtnText === BUTTON_TEXT.INCREASE_LIMIT){
      this.borPicker.hide();
      this.fabBtnText= BUTTON_TEXT.TAKE_MONEY;
      return;
    }
    this.fabBtnText= BUTTON_TEXT.INCREASE_LIMIT;
    this.hideBars.changeTabBarsElementBottom('-5rem');
    this.borPicker.show();
  }

  /*** borrow-progress模态操作
   * */
  private changeBorrowProgress(): void
  {
    if(this.fabBtnText === BUTTON_TEXT.INCREASE_LIMIT){
      this.borProgress.hide();
      this.fabBtnText= BUTTON_TEXT.PROGRESS;
      return;
    }
    this.fabBtnText= BUTTON_TEXT.INCREASE_LIMIT;
    this.hideBars.changeTabBarsElementBottom('-5rem');
    this.borProgress.show();
  }

  /*** 得到选中的数据
  * */
  selectedVal(event): void
  {
    this.authService.getAuth()
      .first()
      .subscribe(auth=> {
      if(auth.hasError) // 未登录
      {
        const modal = this.modalCtrl.create(PageConstant.LoginPage, {},{
          showBackdrop: false,
          enableBackdropDismiss: false,
        });
        modal.present();
        return;
      }

      // 去借款详情
      this.borrowService.getBorrowDetails( {...event.value,...this.userInfo }, this.navCtrl);
    });
  }

  /*** picker离开
  * */
  cancelEvent(event): void
  {
    this.addaOpacityByTimer();
    if(!this.borrowModalStatus)
    {
      this.fabBtnText= BUTTON_TEXT.TAKE_MONEY;
    }else{
      this.fabBtnText= BUTTON_TEXT.PROGRESS;
    }
    this.hideBars.changeTabBarsElementBottom('0');
  }

  /*** 上拉刷新
   * */
  executeRefresh(refresher: Refresher)
  {
    this.isCanNextBool= false; // 初始化开关
    this.setBorrowStoreFromBack(refresher); // 默认进来都会先去查询这个接口。
  }

}
